package com.wellink.demo1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;

import java.util.LinkedList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ListView listView;
    private ImageButton btnAdd;
    private ImageButton btnUpadate;
    private ImageButton btnDel;
    private ImageButton btnClear;

    private MyAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listview);
        btnAdd = findViewById(R.id.btnAdd);
        btnUpadate = findViewById(R.id.btnUpdate);
        btnDel = findViewById(R.id.btnDel);
        btnClear = findViewById(R.id.btnClear);

        View emptyView = findViewById(R.id.emptyText);
        listView.setEmptyView(emptyView);

        List<DataItem> items = new LinkedList<>();
        adapter = new MyAdapter(this,items);
        listView.setAdapter(adapter);

        btnAdd.setOnClickListener(this);
        btnUpadate.setOnClickListener(this);
        btnDel.setOnClickListener(this);
        btnClear.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnAdd:
                addItem();
                break;
            case R.id.btnUpdate:
                updateItem();
                break;
            case R.id.btnDel:
                delItem();
                break;
            case R.id.btnClear:
                clearData();
                break;
                default:
                    break;

        }

    }

    protected void addItem(){
        int pos = getRandPosition();
        adapter.add(pos,new DataItem(R.drawable.icon1,"随机添加"+pos));
    }

    protected void updateItem(){
        int pos = getRandPosition();
        adapter.update(pos,new DataItem(R.drawable.icon2,"更新"+pos));
    }

    protected void delItem(){
        int pos = getRandPosition();
        adapter.remove(pos);
    }

    protected void clearData(){
        adapter.clear();
    }

    protected int getRandPosition(){
        int count = adapter.getCount();
        return (int)(Math.random()*count);
    }
}
